package com.chang.xmltx.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

@Repository
public class BookDaoImpl implements BookDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    // 同一个Service类中的方法相互调用需要使用注入的对象来调用，不要直接使用this.方法名来调用，this.方法名调用是对象内部方法调用，不会通过Spring代理，也就是事务不会起作用
    @Autowired
    private BookDaoImpl bookDao;

    @Override
    public Integer getBookPriceById(Integer bookId) {
        String sql = "select price from t_book where book_id=?";
        Integer price = jdbcTemplate.queryForObject(sql, Integer.class, 1);
        return price;
    }

    @Override
    public void updateStock(Integer bookId) {
        String sql1 = "select stock from t_book where book_id=?";
        Integer stock = jdbcTemplate.queryForObject(sql1, Integer.class, bookId);
        stock = stock - 1;
        String sql = "update t_book set stock=? where book_id=?";
        jdbcTemplate.update(sql, stock, bookId);
    }

    @Override
    public void updateUserBalance(Integer userId, Integer bookId) {


        Integer rows = null;
        // 查询书本价格
        String sql1 = "select price from t_book where book_id=?";
        Integer price = jdbcTemplate.queryForObject(sql1, Integer.class, bookId);
        // 查询用户余额
        String sql2 = "select balance from t_user where user_id=?";
        Integer balance = jdbcTemplate.queryForObject(sql2, Integer.class, userId);
        balance = balance - price;
        /*if (balance < 0) {
            System.out.println("购买失败,账户余额不足");
        } else {*/
            bookDao.updateStock(bookId);
            String sql3 = "update t_user set balance=? where user_id=?";
            rows = jdbcTemplate.update(sql3, balance, userId);
        //}
        System.out.println("执行完毕,影响行数为:" + rows);

    }


}
